/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
			name : 'outline',
			title : '外形层',
			type : 'LineEdit',
			property : {tool_tip : '支持正则匹配'},
        },
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 铺铜 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
require("topsin.genmath");
var genMath = new GenMath();
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		outline:"ol",
		units:"mm"
	}
	var jtg_inner_layer_avoid_copper = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_inner_layer_avoid_copper"}) * 2000 - 200
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
	}
	
	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	var rout = "ol-tz";
	if(!GEN.isLayerExists({job:job, layer:rout})){
		rout = par.outline
	}
	var tmp = rout + '_tmp'
	if(!GEN.isLayerExists({job:job, layer:tmp})){
		GEN.deleteLayer({job:job, layer:[tmp]})
    }
    var matrix = GEN.getMatrix({job:job})
    var work_layers = Object.keys(matrix).filter(function(v) {
        var layer_info = matrix[v];
        return layer_info.context == "board" && layer_info.layer_type=="signal" && layer_info.side == "inner"
    })
	steplist.forEach(function(step) {
		GEN.openStep({job:job, name:step})
        GEN.units({type:par.units})
		GEN.clearLayers()
		GEN.workLayer({name:rout,display_number:2,clear_before:'yes'})
		GEN.selectByFilter({profile:"in"})
		if(GEN.getSelectCount() > 0) {
			GEN.selMoveOther({target_layer:tmp,invert:'no',dx:0,dy:0,size:0})
			GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'});
			(function(){
				GEN.selRefFeat({layers:rout,use:"filter",mode:"touch"});
				if(GEN.getSelectCount() > 0) {
					GEN.selMoveOther({target_layer:rout,invert:'no',dx:0,dy:0,size:0})
					arguments.callee()
				}
			})();
			// 过滤外形线
			if(!GEN.isLayerExists({job:job, layer:tmp + "2"})){
				GEN.deleteLayer({job:job, layer:[tmp + "2"]})
			}
			GEN.COM("profile_to_rout,layer="+tmp + "2"+",width=1")
			GEN.selRefFeat({layers:tmp + "2",use:"filter",mode:"touch"});
			(function(){
				GEN.selRefFeat({layers:rout,use:"filter",mode:"touch"});
				if(GEN.getSelectCount() > 0) {
					GEN.selMoveOther({target_layer:rout,invert:'no',dx:0,dy:0,size:0})
					arguments.callee()
				}   
			})();
			GEN.deleteLayer({job:job, layer:[tmp + "2"]})
			GEN.selAllFeat()
			if(GEN.getSelectCount() > 0) {
				// 继续过滤
				if(GEN.isLayerExists({job:job, layer:tmp+"_f"})){
					GEN.deleteLayer({job:job, layer:[tmp + "_f"]})
				}
				GEN.selCopyOther({dest:'layer_name',target_layer:tmp + "_f",invert:'no',dx:0,dy:0,size:0})
				GEN.workLayer({name:tmp + "_f",display_number:2,clear_before:'yes'})
				GEN.COM("sel_cut_data,det_tol=25.4,con_tol=25.4,rad_tol=0,filter_overlaps=no,delete_doubles=no,use_order=yes,ignore_width=yes,ignore_holes=none,start_positive=yes,polarity_of_touching=same")
				GEN.selRefFeat({layers:"drl",use:"filter",mode:"touch"})
				if(GEN.getSelectCount() > 0) {GEN.selDelete()}
				GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'});
				GEN.selRefFeat({layers:tmp + "_f",use:"filter",mode:"touch"})
				GEN.selReverse()
				if(GEN.getSelectCount() > 0) {
					GEN.selMoveOther({target_layer:rout,invert:'no',dx:0,dy:0,size:0})
				}
				GEN.deleteLayer({job:job, layer:[tmp + "_f"]})
				// 对单边>=20000um的闭合图形铺铜
				// 将长度 >= 20000的线选出来 将跟此线xy坐标相同的线选出来拷贝到辅助层 cuttingdata 拷贝回去
				if(GEN.isLayerExists({job:job, layer:tmp+"_2"})){
					GEN.deleteLayer({job:job, layer:[tmp + "_2"]})
				}
				var feats = GEN.getFeatures({job:job,step:step,layer:tmp,units:"mm",options:"feat_index"})
				feats.forEach(function(item){
					if(item.type == "line") {
						var len = Math.sqrt((item.xe-item.xs)*(item.xe-item.xs) + (item.ye-item.ys)*(item.ye-item.ys))
						if(len >= 20) {
							GEN.selLayerFeat({layer:tmp,index:item.index,operation:"select"})
							if(GEN.getSelectCount() > 0) {GEN.selMoveOther({target_layer:tmp+"_2",invert:'no',dx:0,dy:0,size:0})}
						}
					} else if (item.type == "arc") {
						var len = genMath.arcLength(item)
						if(len >= 20) {
							GEN.selLayerFeat({layer:tmp,index:item.index,operation:"select"})
							if(GEN.getSelectCount() > 0) {GEN.selMoveOther({target_layer:tmp+"_2",invert:'no',dx:0,dy:0,size:0})}
						}
					}
				})
				if(GEN.isLayerExists({job:job, layer:tmp+"_2"})){
					(function(){
						GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'});
						GEN.selRefFeat({layers:tmp+"_2",use:"filter",mode:"touch"})
						if(GEN.getSelectCount() > 0) {
							GEN.selMoveOther({target_layer:tmp+"_2",invert:'no',dx:0,dy:0,size:0})
							arguments.callee()
						}
					})()
					GEN.workLayer({name:tmp+"_2",display_number:2,clear_before:'yes'});
					GEN.selCopyOther({dest:'layer_name',target_layer:rout,invert:'no'})
					GEN.COM("sel_cut_data,det_tol=25.4,con_tol=25.4,rad_tol=0,filter_overlaps=no,delete_doubles=no,use_order=yes,ignore_width=yes,ignore_holes=none,start_positive=yes,polarity_of_touching=same")
                    // 拷贝到负层
                    work_layers.forEach(function(l){
                        GEN.selCopyOther({dest:'layer_name',target_layer:l,invert:'no',dx:0,dy:0,size:-500})
                    })
                    GEN.deleteLayer({job:job, layer:[tmp + "_2"]})
				}
			}
			GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'})
			GEN.selMoveOther({target_layer:rout,invert:'no',dx:0,dy:0,size:0})
			GEN.displayLayer({name:rout, number:1})
			GEN.deleteLayer({job:job, layer:[tmp]})
			// 删除+++
			var matrix = GEN.getMatrix({job:job})
			Object.keys(matrix).forEach(function(v) {
				if(/\+\+\+$/.test(v)){
					GEN.deleteLayer({job:job, layer:[v]})
				}
			})
		}
	})
	
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}
